package com.googlecode.monitoring.service;

import com.googlecode.monitoring.config.SpringApplicationContext;
import com.googlecode.monitoring.dao.AgentConfigurationDao;
import com.googlecode.monitoring.model.ItemToCheck;
import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.JobDetailBean;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(value = "cronTriggerFactory")
public class DefaultCronTriggerFactory implements CronTriggerFactory {
	private AgentConfigurationDao agentConfigurationDao;
	Logger log = Logger.getLogger(DefaultCronTriggerFactory.class);

	@Override
	public Map<JobDetailBean, CronTrigger> buildCronTriggerBeanMap() throws ParseException {
		List<ItemToCheck> itemsList = agentConfigurationDao.getAllItemsFromConfiguration();
		Map<JobDetailBean, CronTrigger> cronTriggerMap = new HashMap<JobDetailBean, CronTrigger>();
		for (ItemToCheck itemToCheck : itemsList) {
			JobDetailBean jobDetailBean = SpringApplicationContext.getBean(JobDetailBean.class);
			jobDetailBean.getJobDataMap().put("item", itemToCheck);
			jobDetailBean.setName(itemToCheck.getId());
			jobDetailBean.setGroup(itemToCheck.getId() + "JobGroup");

			CronTrigger cronTrigger = new CronTrigger(
				itemToCheck.getId() + "trigger",
				itemToCheck.getId() + "Group",
				itemToCheck.getId(),
				itemToCheck.getId() + "JobGroup",
				itemToCheck.getEventTime().getCron());


			cronTriggerMap.put(jobDetailBean, cronTrigger);
			log.debug(itemToCheck.getEventTime().getCron() + "created cron trigger = " + cronTrigger + "; ");
		}
		return cronTriggerMap;
	}

	@Autowired
	public void setInstanceToCheckDao(AgentConfigurationDao agentConfigurationDao) {
		this.agentConfigurationDao = agentConfigurationDao;
	}
}
